package flyingpig.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.hibernate.annotations.Synchronize;

import com.thoughtworks.xstream.XStream;
import flyingpig.data.dao.ImageInfoHome;
import flyingpig.data.domain.ImageInfo;
import flyingpig.hibernate.HibernateUtil;


public class RequestImageInfos extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Log logger = LogFactory.getLog(RequestImageInfos.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestImageInfos() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String stMaxImageInfos = request.getParameter("maxImageInfos");
		String concept = request.getParameter("concept");
		
		
		int maxImageInfos = 20;
		try{
			maxImageInfos = Integer.parseInt(stMaxImageInfos);
		}
		catch(Exception e){
			maxImageInfos = 20;
		}
		
		if(maxImageInfos <= 0) maxImageInfos = 20;
		
		
		XStream xs = new XStream();
		xs.alias("ImageInfo", ImageInfo.class);
		List imageInfos = getUncachedImages(concept, maxImageInfos);		
		
		for (int i = 0; i < imageInfos.size(); i++) {
			// Xstream xml 			
			xs.toXML((ImageInfo)imageInfos.get(i), response
					.getOutputStream());
			if (i != imageInfos.size() - 1) {
				response.getOutputStream().println();
				response.getOutputStream().println("<Seperator/>");
			}
		}

		response.getOutputStream().flush();
		response.getOutputStream().close();
	}
	
	synchronized private List getUncachedImages(String concept, int maxImageInfos){
		Transaction tx = HibernateUtil.getCurrentSession().beginTransaction();
		try {
			ImageInfoHome dao = new ImageInfoHome();
			List imageInfos = dao.findUnCachedImages(concept, maxImageInfos);

			for (Object object : imageInfos) {
				ImageInfo ii = (ImageInfo) object;
				ii.setCacheState("CACHING");
			}
			tx.commit();
			return imageInfos;
			
		} catch (HibernateException e) {
			logger.info("rollback");
			tx.rollback();
			throw e;
		}
	}
}
